﻿CREATE PROCEDURE [dbo].[s_Borrower_Add]
	@LoanID int,
	@Pos int = -1,
	@BorrowerFromID int = NULL
AS
SET NOCOUNT ON

IF @Pos < 0 SELECT @Pos = ISNULL(MAX(Pos)-@Pos,0) FROM t_Loan_Borrower WHERE LoanID = @LoanID

DECLARE @BorrowerID int

WHILE NOT EXISTS(SELECT * FROM t_Loan_Borrower WHERE LoanID = @LoanID AND Pos = @Pos) BEGIN

	INSERT INTO t_Borrower DEFAULT VALUES

	SET @BorrowerID = IDENT_CURRENT('t_Borrower')

	INSERT INTO t_Loan_Borrower (LoanID,BorrowerID,Pos)
	SELECT @LoanID,@BorrowerID,
				 (SELECT ISNULL(MAX(Pos)+1,0) FROM t_Loan_Borrower WHERE LoanID = @LoanID)

	IF @BorrowerFromID > 0 BEGIN
		RAISERROR('Borrower clonning is must be implemented',16,1)
	END

END

RETURN ISNULL(@BorrowerID,0)



